package com.jy.phonemng.biz.user.service;

import javax.annotation.PostConstruct;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.jy.phonemng.biz.dal.model.User;
import com.jy.phonemng.biz.utils.UserLogUtils;
import com.jy.phonemng.framework.utils.security.Md5Utils;
import com.jy.phonemng.sys.exception.UserPasswordNotMatchException;
import com.jy.phonemng.sys.exception.UserPasswordRetryLimitExceedException;

@Service
public class PasswordService {

    @Autowired
    private CacheManager ehcacheManager;

    private Cache        loginRecordCache;

    @Value(value = "${user.password.maxRetryCount}")
    private int          maxRetryCount = 10;

    public void setMaxRetryCount(int maxRetryCount) {
        this.maxRetryCount = maxRetryCount;
    }

    @PostConstruct
    public void init() {
        loginRecordCache = ehcacheManager.getCache("loginRecordCache");
    }

    public void validate(User user, String password) {
        String username = user.getUserName();

        int retryCount = 0;

        Element cacheElement = loginRecordCache.get(username);
        if (cacheElement != null) {
            retryCount = (Integer) cacheElement.getObjectValue();
            if (retryCount >= maxRetryCount) {
                UserLogUtils.log(username, "passwordError",
                    "password error, retry limit exceed! password: {},max retry count {}",
                    password, maxRetryCount);
                throw new UserPasswordRetryLimitExceedException(maxRetryCount);
            }
        }

        if (!matches(user, password)) {
            loginRecordCache.put(new Element(username, ++retryCount));
            UserLogUtils.log(username, "passwordError",
                "password error! password: {} retry count: {}", password, retryCount);
            throw new UserPasswordNotMatchException();
        } else {
            clearLoginRecordCache(username);
        }
    }

    public boolean matches(User user, String newPassword) {
        return user.getPassword().equals(
            encryptPassword(user.getUserName(), newPassword, user.getSalt()));//TODO user.getPassword.
    }

    public void clearLoginRecordCache(String username) {
        loginRecordCache.remove(username);
    }

    public String encryptPassword(String username, String password, String salt) {
        return Md5Utils.hash(username + password + salt);
    }

    public static void main(String[] args) {
        User user = new User();
        user.randomSalt();

        System.out
            .println(new PasswordService().encryptPassword("admin", "password", "4waxiBK2YX"));

        System.out.println("user salt:" + user.getSalt());
        String sltString = user.getSalt();
        System.out.println(sltString);
        System.out.println(new PasswordService().encryptPassword("hezheng", "123456", sltString));
    }
}
